<?php
header('Content-type:text/html;charset=utf8');
$config = [
    'host' => 'localhost',
    'user' => 'root',
    'password' => 'root',
    'database' => 'bd_laravel',
    'charset' => 'utf8'
];
try{
    $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s',$config['host'],$config['database'],$config['charset']);
//    $pdo = new PDO($dsn,$config['user'],$config['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_WARNING]);
    $pdo = new PDO($dsn,$config['user'],$config['password']);
    //下面的这种设置方式相当于是跟传入第三个参数一样
//    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
//    $pdo->setAttribute(PDO::ATTR_CASE,PDO::CASE_UPPER);
    if(!isset($_GET['id'])){
        $_GET['id'] = 1;
    }
    //一个sql注入的例子
    //sql注入，代表的就是认为的在浏览器输入sql语句
//    $query = $pdo->query("SELECT * FROM bd_roles where id = {$_GET['id']}");
//    print_r($query->fetchAll(PDO::FETCH_ASSOC));

    #使用预准备进行查询
//    $sql = "SELECT * FROM bd_roles WHERE id=:id";
//    $sth = $pdo->prepare($sql);
//    $sth->execute(['id'=>$_GET['id']]);
//    $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
//    print_r($rows);


    #使用预准备进行增加数据
//    $sql = "INSERT INTO bd_roles (name) VALUES(:title)";
//    $sth = $pdo->prepare($sql);
//    $sth->execute([":title"=>'houdunren.com']);
//    echo $pdo->lastInsertId();


    #使用预准备进行修改
//    $sql = "update bd_roles set name =:name where id = :id";
//    $sth = $pdo->prepare($sql);
//    $sth->execute([':name'=>$_GET['name'],':id'=>$_GET['id']]);


    #使用预准备进行删除操作
//    $sql = "DELETE FROM bd_roles where id = :id";
//    $sth = $pdo->prepare($sql);
//    $sth->execute([':id'=> 1]);


    #使用占位符来构建预准备
//    $sql = 'select * from bd_roles where id = ?';
//    $sth = $pdo->prepare($sql);
//    $sth->execute([$_GET['id']]);
//    print_r($sth->fetchAll());


    #使用占位符来进行添加操作
    $sql = "INSERT INTO bd_roles (name) VALUES(?)";
    $sth = $pdo->prepare($sql);
    $sth->execute(['houdunren.com']);
    echo $pdo->lastInsertId();



}catch (PDOException $e){
    die($e->getMessage());
}